package fun.lifepoem.objutils.utils;

import java.lang.reflect.Field;

public class ObjUtils {

    public static <T> void compareObjValueChange(T oldObj, T newObj) {

        Field[] fields = oldObj.getClass().getDeclaredFields();

        for (Field field : fields) {
            field.setAccessible(true);
            StringBuilder s = new StringBuilder();

            try {
                Object o = field.get(oldObj);
                Object n = field.get(newObj);
                if (changed(o, n)) {
                    s.append("旧值:").append(o).append("新值:").append(n);
                }
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
            System.out.println(s);

        }
    }

    public static boolean changed(Object obj1, Object obj2) {
        if (obj1 == null && obj2 == null) {
            return false;
        }
        String oldValue = obj1 == null ? "" : obj1.toString();
        String newValue = obj2 == null ? "" : obj2.toString();
        return !oldValue.equals(newValue);
    }

}
